#include "logindialog.h"
#include "ui_logindialog.h"
#include <QDebug>
#include <QJsonObject>
#include <httpmgr.h>
#include <QRegularExpression>
#include "global.h"
#include "tcpmgr.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    ui->password_lineEdit->setEchoMode(QLineEdit::Password);
    ui->email_lineEdit->setPlaceholderText("请输入邮箱");
    ui->password_lineEdit->setPlaceholderText("请输入密码");
    connect(ui->register_btn,&QPushButton::clicked,this,&LoginDialog::switchRegister);

    connect(ui->forget_btn,&QPushButton::clicked,this,&LoginDialog::switchReset);//设置忘记密码逻辑

    initHttpHandlers();
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_login_mod_finish,this,
            &LoginDialog::slot_login_mod_finish);
    //连接tcp连接请求的信号和槽函数
    connect(this,&LoginDialog::sig_connect_tcp,TcpMgr::GetInstance().get(),&TcpMgr::slot_tcp_connect);
    //连接tcp管理者发出的成功连接的信号
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_con_success,this,&LoginDialog::slot_tcp_con_finish);
    //连接tcp管理者发出的登录失败的信号
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_login_failed,this,&LoginDialog::slot_login_failed);

    //设置密码可见与不可见
    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible",
                               "visible_hover","");
    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        auto state = ui->pass_visible->GetCurState();
        if(state == ClickLbState::Normal){
            ui->password_lineEdit->setEchoMode(QLineEdit::Password);
        }else{
            ui->password_lineEdit->setEchoMode(QLineEdit::Normal);
        }});
}

LoginDialog::~LoginDialog()
{
    qDebug()<<"~LoginDialog()";
    delete ui;
}

void LoginDialog::showTip(const QString &str, bool ok)
{
    ui->tip_label->setText(str);
    if(ok){
        ui->tip_label->setProperty("state","normal");
    }
    else{
        ui->tip_label->setProperty("state","error");
    }
    repolish(ui->tip_label);
}

void LoginDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips,false);
}

void LoginDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->tip_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

void LoginDialog::initHttpHandlers()
{
    //注册获取登录回包的逻辑
    _handlers.insert(ReqId::ID_LOGIN_USER,[this](const QJsonObject& jsonObject){
        int error = jsonObject["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip("参数错误",false);
            return;
        }
        showTip("登录成功",true);
        auto email = jsonObject["email"].toString();
        //发送信号通知tcpMgr发送长链接
        ServerInfo si;
        si.uid = jsonObject["uid"].toInt();
        si.host = jsonObject["host"].toString();
        si.port = jsonObject["port"].toString();
        si.token = jsonObject["token"].toString();
        _uid = si.uid;
        _token = si.token;
        qDebug()<< "email is " << email << " uid is " << si.uid <<" host is "
                        << si.host << " Port is " << si.port << " Token is " << si.token;
        emit sig_connect_tcp(si);
    });
}

bool LoginDialog::checkEmailValid()
{
    QString email = ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|\_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,"邮箱地址不正确");
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}


void LoginDialog::on_login_btn_clicked()
{

    //emit TcpMgr::GetInstance()->sig_swich_chatdlg();

    if(ui->email_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,"邮箱不能为空");
        return;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    if(!checkEmailValid()){
        AddTipErr(TipErr::TIP_USER_ERR,"邮箱格式不正确");
        return;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    if(ui->password_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,"密码不能为空");
        return;
    }
    DelTipErr(TipErr::TIP_USER_ERR);

    auto email = ui->email_lineEdit->text();
    auto pwd = xorString(ui->password_lineEdit->text());
    //发送http请求登录
    QJsonObject json_obj;
    json_obj["email"] = email;
    json_obj["passwd"] = pwd;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_login"),
                                        json_obj,ReqId::ID_LOGIN_USER,Modules::LOGINMOD);
}

void LoginDialog::slot_login_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS){
        showTip("网络请求错误",false);
        return;
    }
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    //json解析错误
    if(jsonDoc.isNull()){
        showTip("json解析错误",false);
        return;
    }
    if(!jsonDoc.isObject()){
        showTip("json解析错误",false);
        return;
    }
    _handlers[id](jsonDoc.object());
}

void LoginDialog::slot_tcp_con_finish(bool bsuccess)
{
    if(bsuccess){
        showTip("聊天服务器连接成功，正在登录...",true);
        QJsonObject jsonObj;
        jsonObj["uid"] = _uid;
        jsonObj["token"] = _token;
        QJsonDocument doc(jsonObj);
        QByteArray jsonString = doc.toJson(QJsonDocument::Indented);
        //发送tcp请求给chat server
        emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN,jsonString);
    }else{
        showTip("网络异常",false);
    }
}

void LoginDialog::slot_login_failed(int err)
{
    QString result = QString("登录失败:")+QString(err);
    showTip(result,false);
}
